package db

import (
	"GameServer/common"
	"GameServer/common/logger"
	"GameServer/pb"
	"GameServer/redis"
	"encoding/json"
	"errors"
	"strconv"
	"strings"
	"time"
)

type UserGroupData struct {
	Uuid       int32
	Task_state int32
	Fetch_time int32
}

func SliceIntToString(res []int32) string {
	rts := ""
	for key, val := range res {
		rts += strconv.Itoa(int(val))
		if key != len(res)-1 {
			rts += ","
		}
	}
	return rts
}

func StringToSliceInt(res string) []int32 {
	var rtslice []int32
	ss := strings.Split(res, ",")
	for _, val := range ss {
		snum, err := strconv.Atoi(val)
		if err != nil {
			continue
		}
		rtslice = append(rtslice, int32(snum))
	}
	return rtslice
}

func GetSingleValue(cmd string) (string, error) {
	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	var value string
	if err != nil {
		logger.Notic("GetSingleValue Query error:%v cmd:%v", err, cmd)
		return value, err
	}

	for rows.Next() {
		err = rows.Scan(&value)
		if err != nil {
			logger.Notic("GetSingleValue Scan error:%v", err)
			return value, err
		}
		return value, err
	}

	return value, err
}

func GetSingleIntValue(cmd string) (int, error) {
	var val int
	var value string
	var err error
	if value, err = GetSingleValue(cmd); err == nil {
		val, err = strconv.Atoi(value)
	}

	return val, err
}

func GetSingleInt64Value(cmd string) (int64, error) {
	var val int64
	var value string
	var err error
	if value, err = GetSingleValue(cmd); err == nil {
		val, err = strconv.ParseInt(value, 10, 64)
	}

	return val, err
}

func GetTaskListID(uuid uint32) ([]int32, error) {
	stringlist := ""

	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserExtraTaskInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USEREXTRA_DATA, strconv.Itoa(int(uuid)))
		if err != nil {
			logger.Error("GetTaskListID failed err=%v", err)
			return nil, err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("GetTaskListID json failed err=%v", err)
			return nil, err
		}

		return StringToSliceInt(baseinfo.User_data), nil
	}
	// *******************************

	cmd := "select user_data from dtb_user_extratask where uuid = ?"
	rows, err := m_game_db.Query(cmd, uuid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("GetTaskListID Query error:%v cmd:%v", err, cmd)
		return nil, err
	}

	for rows.Next() {
		err = rows.Scan(&stringlist)
		if err != nil {
			logger.Notic("GetAllTaskInfo Scan error:%v", err)
			return nil, err
		}

	}

	return StringToSliceInt(stringlist), nil
}

func GetAllTaskInfo(uid uint32) ([]*pb.QuestItem, error) {
	var rts []*pb.QuestItem
	// *******************************
	if redis.GetRedisIsOpen() {
		rediskey := redis.GS_USERTASK_DATA + strconv.Itoa(int(uid))

		results, err := redis.GetRedisClient().HGetAllValues(rediskey)
		if err != nil {
			logger.Error("GetAllTaskInfo failed err=%v", err)
			return nil, err
		}
		for _, val := range results {
			baseinfo := new(pb.QuestItem)
			err = json.Unmarshal([]byte(val.(string)), baseinfo)
			if err != nil {
				logger.Error("GetAllTaskInfo json failed err=%v", err)
				continue
			}
			rts = append(rts, baseinfo)
		}

		return rts, nil
	}
	// *******************************

	cmd := "select COALESCE(taskid,0),COALESCE(task_state,0),COALESCE(select_item,0),COALESCE(task_startime,0),COALESCE(task_finishtime,0) " +
		"from dtb_user_task where uuid =" + strconv.Itoa(int(uid))

	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("GetAllTaskInfo Query error:%v cmd:%v", err, cmd)
		return nil, err
	}

	for rows.Next() {
		tmpinfo := new(pb.QuestItem)
		err = rows.Scan(&tmpinfo.QuestId, &tmpinfo.State, &tmpinfo.SelectItem, &tmpinfo.StartTime, &tmpinfo.FinishTime)
		if err != nil {
			logger.Notic("GetAllTaskInfo Scan error:%v", err)
			continue
		}

		rts = append(rts, tmpinfo)
	}
	return rts, nil
}

func GMClearUserData(uid uint32) error {
	// *******************************
	if redis.GetRedisIsOpen() {
		rediskey := redis.GS_USERTASK_DATA + strconv.Itoa(int(uid))
		redis.GetRedisClient().Delete(rediskey)
		redis.GetRedisClient().Delete(redis.GS_USERBASE_INFO)
		redis.GetRedisClient().Delete(redis.GS_USERDEVICE_INFO)
		return nil
	}
	// *******************************

	cmd := "delete from dtb_user_task where uuid = ?"
	_, err := m_game_db.Exec(cmd, uid)
	if err != nil {
		return err
	}
	cmd = "delete from dtb_user_main where uuid = ?"
	_, err = m_game_db.Exec(cmd, uid)
	if err != nil {
		return err
	}

	cmd = "delete from dtb_user_deviceinfo where uuid = ?"
	_, err = m_game_db.Exec(cmd, uid)
	if err != nil {
		return err
	}
	return nil
}

func GMOperateTili(uid uint32, optype, opnum int32) error {
	var origintili int
	var newtilint int
	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("GMOperateTili failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("GMOperateTili json failed err=%v", err)
			return err
		}

		if optype == 1 {
			newtilint = origintili + int(opnum)
		} else {
			newtilint = origintili - int(opnum)
			if newtilint < 0 {
				newtilint = 0
			}
		}
		baseinfo.User_tili = int32(newtilint)

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "select user_tili from dtb_user_main where uuid = ? "
	rows, err := m_game_db.Query(cmd, uid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("GMOperateTili Scan error:%v", err)
		return err
	}

	for rows.Next() {

		err = rows.Scan(&origintili)
		if err != nil {
			logger.Notic("GMOperateTili Scan error:%v", err)
			return err
		}

	}

	if optype == 1 {
		newtilint = origintili + int(opnum)
	} else {
		newtilint = origintili - int(opnum)
		if newtilint < 0 {
			newtilint = 0
		}
	}

	cmd = "update dtb_user_main set user_tili = ? where uuid = ?"
	_, err = m_game_db.Exec(cmd, newtilint, uid)
	if err != nil {
		logger.Notic("GMOperateTili Scan error:%v", err)
		return err
	}

	return nil
}

func GMOperateCurLevel(uid uint32, curlv int32) error {

	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("GMOperateCurLevel failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("GMOperateCurLevel json failed err=%v", err)
			return err
		}

		baseinfo.Cur_level = int32(curlv)

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("GMOperateCurLevel err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("GMOperateCurLevel err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "update dtb_user_main set cur_level = ? where uuid = ?"
	_, err := m_game_db.Exec(cmd, curlv, uid)
	if err != nil {
		logger.Notic("GMOperateCurLevel Scan error:%v", err)
		return err
	}

	nowt := time.Now().Unix()
	for i := 100001; i < int(curlv); i++ {
		cmd = "insert into dtb_user_level(uuid,battleid,levelid,start_time,finish_time,level_state) values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE level_state = 1"
		//logger.Info("GMOperateCurLevel cmd=%v", cmd)
		final := int(nowt) + i
		battleid := strconv.Itoa(final)
		_, err := m_game_db.Exec(cmd, uid, battleid, i, nowt, nowt, 1)
		if err != nil {
			logger.Notic("GMOperateCurLevel Scan error:%v", err)
			continue
		}
	}
	return nil
}

func GMOperateItem(uid uint32, plannum, boomnum, rainnum int32) error {

	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("GMOperateCurLevel failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("GMOperateCurLevel json failed err=%v", err)
			return err
		}

		baseinfo.Plan_num = int32(plannum)
		baseinfo.Boom_num = int32(boomnum)
		baseinfo.Rainbow_num = int32(rainnum)

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("GMOperateCurLevel err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("GMOperateCurLevel err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "update dtb_user_main set plan_num = ?,boom_num = ?,rainbow_num = ? where uuid = ?"
	_, err := m_game_db.Exec(cmd, plannum, boomnum, rainnum, uid)
	if err != nil {
		logger.Notic("GMOperateItem Scan error:%v", err)
		return err
	}
	return nil
}

func GMOperateUSD(uid uint32, optype, opnum int32) error {
	var originstar int
	var newstar int

	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("GMOperateTili failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("GMOperateTili json failed err=%v", err)
			return err
		}

		if optype == 1 {
			newstar = originstar + int(opnum)
		} else {
			newstar = originstar - int(opnum)
			if newstar < 0 {
				newstar = 0
			}
		}
		baseinfo.User_star = int32(newstar)

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "select user_dimond from dtb_user_main where uuid = ? "
	rows, err := m_game_db.Query(cmd, uid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("GMOperateUSD Scan error:%v", err)
		return err
	}

	for rows.Next() {

		err = rows.Scan(&originstar)
		if err != nil {
			logger.Notic("GMOperateUSD Scan error:%v", err)
			return err
		}

	}

	if optype == 1 {
		newstar = originstar + int(opnum)
	} else {
		newstar = originstar - int(opnum)
		if newstar < 0 {
			newstar = 0
		}
	}

	cmd = "update dtb_user_main set user_dimond = ? where uuid = ?"
	_, err = m_game_db.Exec(cmd, newstar, uid)
	if err != nil {
		logger.Notic("GMOperateUSD Scan error:%v", err)
		return err
	}

	return nil
}

func GMOperateStar(uid uint32, optype, opnum int32) error {
	var originstar int
	var newstar int

	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("GMOperateTili failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("GMOperateTili json failed err=%v", err)
			return err
		}

		if optype == 1 {
			newstar = originstar + int(opnum)
		} else {
			newstar = originstar - int(opnum)
			if newstar < 0 {
				newstar = 0
			}
		}
		baseinfo.User_dimond = int32(newstar)

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "select user_gold from dtb_user_main where uuid = ? "
	rows, err := m_game_db.Query(cmd, uid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("GMOperateStar Scan error:%v", err)
		return err
	}

	for rows.Next() {

		err = rows.Scan(&originstar)
		if err != nil {
			logger.Notic("GMOperateStar Scan error:%v", err)
			return err
		}

	}

	if optype == 1 {
		newstar = originstar + int(opnum)
	} else {
		newstar = originstar - int(opnum)
		if newstar < 0 {
			newstar = 0
		}
	}

	cmd = "update dtb_user_main set user_gold = ? where uuid = ?"
	_, err = m_game_db.Exec(cmd, newstar, uid)
	if err != nil {
		logger.Notic("GMOperateStar Scan error:%v", err)
		return err
	}

	return nil
}

func CheckSyncID(syncid int64, uid uint32) (error, common.ErrorType) {
	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("CheckSyncID failed err=%v", err)
			return err, common.Error_Op_Db_Failed
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("CheckSyncID json failed err=%v", err)
			return err, common.Error_Op_Db_Failed
		}

		if baseinfo.Sync_id+1 < syncid {
			err = errors.New("SyncID too big")
			logger.Notic("CheckSyncID Scan error:%v", err)
			return err, common.Error_Check_Syncid_Failed
		}

		if baseinfo.Sync_id+1 > syncid {
			err = errors.New("SyncID too small")
			logger.Notic("CheckSyncID Scan error:%v", err)
			return err, common.Error_Check_Syncid_AlreadyHandled
		}

		return nil, common.Error_OK
	}
	// *******************************

	cmd := "select syncid from dtb_user_main where uuid =" + strconv.Itoa(int(uid))

	usesyncid, err := GetSingleInt64Value(cmd)
	if err != nil {
		logger.Notic("CheckSyncID Scan error:%v", err)
		return err, common.Error_Op_Db_Failed
	}

	if usesyncid+1 < syncid {
		err = errors.New("SyncID too big")
		logger.Notic("CheckSyncID Scan error:%v", err)
		return err, common.Error_Check_Syncid_Failed
	}

	if usesyncid+1 > syncid {
		err = errors.New("SyncID too small")
		logger.Notic("CheckSyncID Scan error:%v", err)
		return err, common.Error_Check_Syncid_AlreadyHandled
	}

	return nil, common.Error_OK
}

func UpdateQuestItem(questid, selectitem int32, uid uint32) error {

	// *******************************
	if redis.GetRedisIsOpen() {
		rediskey := redis.GS_USERTASK_DATA + strconv.Itoa(int(uid))
		baseinfo := new(pb.QuestItem)
		val, err := redis.GetRedisClient().HGet(rediskey, strconv.Itoa(int(questid)))
		if err != nil {
			logger.Error("UpdateQuestItem failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("UpdateQuestItem json failed err=%v", err)
			return err
		}

		baseinfo.SelectItem = selectitem

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("UpdateQuestItem err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(rediskey, strconv.Itoa(int(questid)), string(newval))

		if err != nil {
			logger.Error("UpdateQuestItem err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "update dtb_user_task set select_item = ? where uuid = ? and taskid = ? "

	_, err := m_game_db.Exec(cmd, selectitem, uid, questid)
	if err != nil {
		logger.Notic("UpdateQuestItem Scan error:%v", err)
		return err
	}

	return nil
}

func AddSyncIdIndex(uid uint32, setp uint32) (error, int64) {
	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("AddSyncIdIndex failed err=%v", err)
			return err, 0
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("AddSyncIdIndex json failed err=%v", err)
			return err, 0
		}

		baseinfo.Sync_id += 1

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("AddSyncIdIndex err=%v", err)
			return err, 0
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("AddSyncIdIndex err=%v", err)
			return err, 0
		}
		return nil, baseinfo.Sync_id
	}
	// *******************************

	var newsyncid int64
	cmd := "update dtb_user_main set syncid = syncid + ? where uuid = ?"
	_, err := m_game_db.Exec(cmd, setp, uid)
	if err != nil {
		logger.Notic("AddSyncIdIndex Scan error:%v", err)
		return err, 0
	}
	cmd = "select syncid from dtb_user_main where uuid = ?"
	rows, err := m_game_db.Query(cmd, uid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("AddSyncIdIndex Scan error:%v", err)
		return err, 0
	}

	for rows.Next() {
		err = rows.Scan(&newsyncid)
		if err != nil {
			logger.Notic("AddSyncIdIndex Scan error:%v", err)
			return err, 0
		}

	}

	return nil, newsyncid
}

func CheckQuestFinished(uid uint32, pretaskid int32) error {
	// *******************************
	if redis.GetRedisIsOpen() {
		rediskey := redis.GS_USERTASK_DATA + strconv.Itoa(int(uid))
		baseinfo := new(pb.QuestItem)
		val, err := redis.GetRedisClient().HGet(rediskey, strconv.Itoa(int(pretaskid)))
		if err != nil {
			logger.Error("CheckQuestFinished failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("CheckQuestFinished json failed err=%v", err)
			return err
		}

		if baseinfo.State != 1 {
			return errors.New("quest not finished")
		}

		return nil
	}
	// *******************************

	var ts int
	cmd := "select task_state from dtb_user_task where uuid = ? and taskid = ?"
	rows, err := m_game_db.Query(cmd, uid, pretaskid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("CheckQuestFinished Scan error:%v", err)
		return err
	}

	for rows.Next() {
		err = rows.Scan(&ts)
		if err != nil {
			logger.Notic("CheckQuestFinished Scan error:%v", err)
			return err
		}
	}

	if ts != 1 {
		return errors.New("quest not finished")
	}
	return nil
}

func UpdateFinTaskExtra(req *pb.GameQuestFinishOfflineReq, uid uint32) error {
	data := SliceIntToString(req.Tasklist)

	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserExtraTaskInfo)
		baseinfo.User_data = data
		baseinfo.Uuid = int32(uid)
		baseinfo.New_taskid = req.QuestId

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("UpdateFinTaskExtra err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USEREXTRA_DATA, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("UpdateFinTaskExtra err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "insert into dtb_user_extratask(uuid,newest_taskid,user_data) values(?,?,?) ON " +
		"DUPLICATE KEY UPDATE newest_taskid = ?,user_data = ?"
	_, err := m_game_db.Exec(cmd, uid, req.QuestId, data, req.QuestId, data)
	if err != nil {
		logger.Notic("UpdateFinTaskExtra Scan error:%v", err)
		return err
	}
	return nil
}

func UpdateFinsTask(req *pb.GameQuestFinishOfflineReq, uid uint32, coststar int32) error {

	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserBaseInfo)
		val, err := redis.GetRedisClient().HGet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)))
		if err != nil {
			logger.Error("GMOperateTili failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("GMOperateTili json failed err=%v", err)
			return err
		}

		baseinfo.User_star -= coststar

		newval, err := json.Marshal(baseinfo)
		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERBASE_INFO, strconv.Itoa(int(uid)), string(newval))

		if err != nil {
			logger.Error("GMOperateTili err=%v", err)
			return err
		}

		//然后插入数据
		questinfo := new(pb.QuestItem)
		questinfo.QuestId = req.QuestId
		questinfo.State = req.State
		questinfo.SelectItem = req.SelectItem
		questinfo.FinishTime = req.BaseInfo.SvrFinishTime
		questinfo.StartTime = req.BaseInfo.SvrOccurTime

		ssval, err := json.Marshal(questinfo)
		if err != nil {
			logger.Error("UpdateFinTaskExtra err=%v", err)
			return err
		}

		rediskey := redis.GS_USERTASK_DATA + strconv.Itoa(int(uid))
		err = redis.GetRedisClient().HSet(rediskey, strconv.Itoa(int(req.QuestId)), string(ssval))

		if err != nil {
			logger.Error("UpdateFinTaskExtra err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	//先更新基本数据
	cmd := "update dtb_user_main set user_gold = user_gold-? where  uuid = ? "
	_, err := m_game_db.Exec(cmd, coststar, uid)
	if err != nil {
		logger.Notic("UpdateFinsTask Scan error:%v", err)
		return err
	}

	//下面更新任务相关数据
	cmd = "insert into dtb_user_task(uuid,taskid,task_state,select_item,task_startime,task_finishtime) values(?,?,?,?,?,?) "
	_, err = m_game_db.Exec(cmd, uid, req.QuestId, req.State, req.SelectItem, req.BaseInfo.SvrOccurTime, req.BaseInfo.SvrFinishTime)
	if err != nil {
		logger.Notic("UpdateFinsTask Scan error:%v", err)
		return err
	}
	return nil
}

func IsTaskGroupFetched(uid uint32, taskid int32) bool {
	// *******************************
	if redis.GetRedisIsOpen() {
		baseinfo := new(UserGroupData)
		rediskey := redis.GS_USERGROUP_DATA + strconv.Itoa(int(uid))
		val, err := redis.GetRedisClient().HGet(rediskey, strconv.Itoa(int(taskid)))
		if err != nil {
			logger.Error("IsTaskGroupFetched failed err=%v", err)
			return false
		}
		err = json.Unmarshal([]byte(val), baseinfo)
		if err != nil {
			logger.Error("IsTaskGroupFetched json failed err=%v", err)
			return false
		}

		if baseinfo.Task_state == -1 {
			return false
		}

		return true
	}
	// *******************************

	state_ := -1

	row := m_game_db.QueryRow("select task_state from dtb_user_gruoptaskdata where uuid = ? and task_id = ?", uid, taskid)
	err := row.Scan(&state_)

	if err != nil || state_ == -1 {
		//logger.Notic("IsTaskGroupFetched error:%v", err)
		return false
	}

	return true
}

func UpdateTaskGroupFetched(uid uint32, taskid int32) error {

	// *******************************
	if redis.GetRedisIsOpen() {

		info := new(UserGroupData)
		info.Task_state = 1
		info.Uuid = int32(uid)
		info.Fetch_time = int32(time.Now().Unix())
		rediskey := redis.GS_USERGROUP_DATA + strconv.Itoa(int(uid))

		val, err := json.Marshal(info)
		if err != nil {
			logger.Error("UpdateTaskGroupFetched err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(rediskey, strconv.Itoa(int(taskid)), string(val))

		if err != nil {
			logger.Error("UpdateTaskGroupFetched err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	_, err := m_game_db.Exec("insert into dtb_user_gruoptaskdata(uuid,task_id,task_state,fetch_time) values(?,?,?,?)", uid, taskid, 1, time.Now().Unix())
	if err != nil {
		logger.Notic("UpdateTaskGroupFetched Scan error:%v", err)
		return err
	}

	return nil
}
